import androidhelper
import time
import sys
import re
from requests.packages.urllib3.util import Retry
from requests.adapters import HTTPAdapter
from requests import Session, exceptions
import threading

command = None


def set_command():
    global command
    while True:
        f = open('command.txt', mode='r')
        c = f.readline()
        # print('##' + str(c) + '##')
        # f.seek(0)
        # f.write('None')
        f.close()
        if c in ('pause', 'unpause', 'stop', 'exit', 'next', 'pre'):
            command = c
            # print('change status')
        # else:
        #     print(c)
        time.sleep(2)


def speak(item_id):
    global command
    droid = androidhelper.Android()

    u = 'http://zjl.hmxingkong.com/n/novel/getItemContent?itemId='
    u += item_id
    s = Session()
    s.mount('http://', HTTPAdapter(
        max_retries=Retry(total=5, status_forcelist=[500])
        )
    )
    r = s.get(u, timeout=10)

    json_data = r.json()
    next_id = json_data['data']['novelItem']['nextId']
    pre_id = json_data['data']['novelItem']['preId']
    title = json_data['data']['novelItem']['title']
    print('next_id\t', next_id)
    # print(json_data)
    text = json_data['data']['content']
    if text is None or text == '':
        u = 'http://zjl.hmxingkong.com/n/novel/content/' + item_id
        r = s.get(u, timeout=10)
        text = r.text
    text = text.replace('&nbsp;', '').replace('<br/>', '\n')
    text = text.replace('<br />', '\n').replace('\n\n', '\n').replace('\n\n', '\n')
    pats = ['(<title>.*?</title>)', '(<.*?>)']
    for pat in pats:
        results = re.compile(pat, re.S).findall(text)
        for result in results:
            text = text.replace(result, '')
    
    splits = text.split('。')
    splits.insert(0, title)
    for i in range(0, len(splits)):
        splits[i] = splits[i] + '。'
    splits.append('本章完')
    i = 0
    # st = time.time()
    # af = open('af_' + item_id + '.log', mode='w')
    while True:
        if command == 'pause':
            time.sleep(2)
            continue
        if command == 'stop':
            i = 0
            time.sleep(2)
            continue
        if command == 'next':
            command = None
            return next_id
        if command == 'pre':
            command = None
            return pre_id
        if command == 'exit':
            sys.exit()
        
        # if True:
        if not droid.ttsIsSpeaking().result:
            if i >= len(splits):
                break
            # af.write(str(time.time() - st) + '\n')
            # af.write(str(len(splits[i])) + '\t')
            content = splits[i]
            content = content.replace(' ', '')
            droid.ttsSpeak(content)
            # st = time.time()
            
            show_text = splits[i]
            if i > 0:
                show_text = splits[i - 1] + '\n' + show_text
            if i + 1 < len(splits):
                show_text = show_text + '\n' + splits[i + 1]
            # droid.dialogCreateAlert(splits[0] + str(i) + '/' + str(len(splits)), show_text)
            # droid.dialogSetNeutralButtonText('取消')
            # droid.dialogShow()
            
            print(i + 1, '/', str(len(splits)), ' ', splits[i])
            time.sleep(0.147860385 * len(content))
            i += 1
            continue
        print('*', end=' ')
        time.sleep(0.3)
        # print('sleep\t', i, droid.ttsIsSpeaking())

    print('----------end!\t', item_id)
    # af.write(str(time.time() - st) + '\n')
    # af.flush()
    # af.close()
    return next_id


def main():
    droid = androidhelper.Android()
    
    t = threading.Thread(target=set_command, args=[])
    t.setDaemon(True)
    t.start()
    
    # item_id = 358326
    item_id = None
    if item_id is None:
        line = droid.dialogGetInput('输入阅读章节ID')
        item_id = line.result
    while not item_id is None:
        print('############## speak\t', item_id)
        f = open('command.txt', mode='r+')
        f.write(str(item_id))
        f.flush()
        f.close()
        item_id = speak(str(item_id))


if __name__ == "__main__":
    main()
